//const Domain = "http://localhost:15000/";
const Domain = "http://common.qiyedaishu.com";
import md5 from "@/utils/md5.js";
import Validate from "@/utils/validate.js";
const FormatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(FormatNumber).join('/') + ' ' + [hour, minute, second].map(FormatNumber).join(':')
}
const Audit={
	Zero:0,
	One:1,
	Two:2,
	Three:3,
	Four:4,
	Five:5,
	Six:6
};
const FormatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
String.prototype.RHtml = function () {
  return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, "");
};

String.prototype.ReplaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

String.prototype.Contain = function (str) {
    return this.indexOf(str)>-1?true:false;
};

String.prototype.TranImg = function (str) {
    return this.ReplaceAll("<img","<img style='width:100%;' ");
};

String.prototype.IsEmpty = function (str) {
    return (Validate.IsEmpty(str) || str==Domain);
};
Array.prototype.Remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.RemoveAt = function (index) {
    if (isNaN(index) || index >= this.length) {
        return false;
    }
    this.splice(index, 1);
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};

Array.prototype.Max = function () {
  return Math.max.apply(Math, this);
};

Array.prototype.Min = function () {
  return Math.min.apply(Math, this);
};
String.prototype.ToDate = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy-MM-dd");
};
String.prototype.ToDateTwo = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy.MM.dd");
};
String.prototype.ToDayTime = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("MM-dd hh:mm");
};
String.prototype.ToMinute = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy年MM月dd日hh时mm分");
};
String.prototype.ToYear = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy");
};
String.prototype.ReplacePlus = function () {
	var str=this;
	while(str.indexOf('+')>-1){
		str=str.replace('+','%2B');
	}
	return str;
};
String.prototype.GetImg = function(size)
{
    if (this) {
        var files = this.split('.');
        if (files.length >= 2) {
            var ext = "." + files[files.length - 1];
            return this.replace(ext, "") + "_" + size + ext;
        } else {
            return this;
        }
    }else{
		return this;
	}
};
Number.prototype.ToString = function () {
    return this.toString();
};
Number.prototype.ToEmpty = function () {
	if(this==0 || !this){
		return "";
	}else{
		return this+"";
	}
};
//四舍五入保留2位小数
Number.prototype.ToPrice = function () {
    return (Math.round(this * 100) / 100).toFixed(2);
};
Number.prototype.ToSize = function() {
    var size = this / 1024;
    if (size < 1024) {
        return size.toFixed(2) + " KB";
    }
    else if(size>=1024 && size<1048576) {
        return (size / 1024).toFixed(2) + " MB";
    }
    else {
        return (size / 1024 / 1024).toFixed(2) + " GB";
    }
};
Date.prototype.Format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};
Date.prototype.AddDays = function (d) {
    return new Date(this.setDate(this.getDate() + d));
};
function Loading(title){
	uni.showLoading({
	    title: title
	});
};

function HideLoading(){
	uni.hideLoading();
};

function Toast(title, callback){
	uni.showToast({
	    title: title,
		icon: "none",
		position: "bottom",
	    duration: 2000,
		success: function (res) {
			setTimeout(function(){
				callback && callback();
			},1000);
		}
	});
};

function Success(title){
	uni.showToast({
	    title: title,
	    duration: 2000
	});
};

function Fail(title){
	uni.showToast({
	    title: title,
		image: "http://gongxianggudong.qiyedaishu.com/static/image/error.png",
	    duration: 2000
	});
};

function Alert(title, callback){
	uni.showModal({
	    title: "提示",
	    content: title,
		showCancel: false,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            
	        }
	    }
	});
}

function Confirm(title, callback, cancel){
	uni.showModal({
	    title: "提示",
	    content: title,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            cancel && cancel();
	        }
	    }
	});
}
function LoadMore(data,callback){
	Post(data, json=>{
		callback && callback(json.Data.List);
	});
}
function Post(data, callback) {
  data.Timestamp = new Date().getTime();
  data.Token =  uni.getStorageSync("Token") || '';
  data.Sign = md5.GetSign(data);
  data.Source = 3;
  uni.request({
  		url: Domain+"/tools/API.ashx",
  		data: data,
		header:{'Content-Type' : 'application/x-www-form-urlencoded'},
		method:'POST',
  		success: (json) => {
			console.log(json);
  			if(json.data.State){
  				callback && callback(json.data);
  			}else{
				if(json.data.Code=="401"){
					uni.stopPullDownRefresh();
					Toast(json.data.Msg, item=>{
						if(Ticker(2)){
							uni.navigateBack({delta:-1});
							uni.navigateTo({
								url:'/pages/index/login'
							});
						}
					});
				}else{
					callback && callback(json.data);
				}
  			}
  		},
  		fail(json) {
  			Toast(json.data.Msg);
  		}
  });
};
function PostAdmin(data, callback) {
  data.Timestamp = new Date().getTime();
  data.Token =  uni.getStorageSync("Token") || '';
  data.Sign = md5.GetSign(data);
  data.Source = 3;
  uni.request({
  		url: Domain+"/tools/Admin.ashx",
  		data: data,
		header:{'Content-Type' : 'application/x-www-form-urlencoded'},
		method:'POST',
  		success: (json) => {
  			if(json.data.State){
  				callback && callback(json.data);
  			}else{
				if(json.data.Code=="401"){
					uni.stopPullDownRefresh();
					Toast(json.data.Msg, item=>{
						if(Ticker(2)){
							uni.navigateBack({delta:-1});
							uni.navigateTo({
								url:'/pages/index/login'
							});
						}
					});
				}else{
					callback && callback(json.data);
				}
  			}
  		},
  		fail(json) {
  			Toast(json.data.Msg);
  		}
  });
};
function Ticker(Second){
	var OldTime = uni.getStorageSync("Time");
	if(!OldTime){
		uni.setStorageSync("Time",new Date().Format("yyyy-MM-dd hh:mm:ss"));
		return true;
	}else{
		var NewTime=new Date().Format("yyyy-MM-dd hh:mm:ss");
		uni.setStorageSync("Time",NewTime);
		if(DateDiff("s",OldTime, NewTime)>Second){
			return true;
		}else{
			return false;
		}
		
	}
};
function Upload(paths, handle, list, callback){
	var path = paths.pop();
	uni.uploadFile({
		  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
		  filePath: path,
		  name: 'img',
		  formData: {handle:handle},
		  success: json=> {
			  list.push(JSON.parse(json.data).Data.Path);
			  if(paths.length > 0){
			      Upload(paths, handle, list, callback);
			  }else{
			      callback(list);
			  }
		  }
	});
};
function DownloadApp(url,callback){
	var task = plus.downloader.createDownload( url, {}, function ( d, status ) {  
	    if ( status == 200 ) { // 下载成功
	        var path = d.filename;
	        plus.runtime.install(path);  // 安装下载的apk文件
	    } else {//下载失败
	        Alert("下载失败");
	    }
	});  
	task.addEventListener("statechanged", function (download, status) {
		switch (download.state) {
			case 3:
				var percent = (download.downloadedSize / download.totalSize * 100).toFixed(0);
				if(callback){callback(percent);}
				break;
		}
	});
	task.start();
};
function DownloadWgt(url,callback){
	var task = plus.downloader.createDownload( url, {}, function ( d, status ) {  
	    if ( status == 200 ) { // 下载成功
	        var path = d.filename;
	        plus.runtime.install(path,{force:true},function(){
				if(callback){callback();}
				Confirm("新版本已自动升级成功，需要重启", obj=>{
					plus.runtime.restart();
				})
			});  // 安装下载的apk文件
	    }
	});  
	task.start(); 
};
function OneUpload(path, handle, callback){
	if(path!='' && path.indexOf("http")==-1){
		uni.uploadFile({
			  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
			  filePath: path,
			  name: 'img',
			  formData: {handle:handle},
			  success: json=> {
				  if(callback){callback(JSON.parse(json.data).Data.Path);}
			  }
		});
	}else{
		if(callback){callback(path);};
	}
};
function ScanUpload(path, handle, callback){
	uni.uploadFile({
		  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
		  filePath: path,
		  name: 'img',
		  formData: {handle:handle},
		  success: json=> {
			  if(callback){callback(JSON.parse(json.data).data);}
		  }
	});
};
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return "";
}

function GCJ02ToBaiDu(value) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var ll = value.split(",");
    var x = ll[1], y = ll[0];
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    return  (z * Math.sin(theta) + 0.006)+ ',' + (z * Math.cos(theta) + 0.0065);
}
function SetTabBarBadge(Count){
	if(Count>0){
		uni.setTabBarBadge({
			index: 3,
			text: Count.toString()
		});
		// #ifdef APP-PLUS
		plus.runtime.setBadgeNumber(Count);
		// #endif
	}else{
		uni.removeTabBarBadge({
			index:3
		});
	}
}
function ListToImgs(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Name+"*"+item.Path);
	});
	return array.join(",");
};
function ListToPaths(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Path);
	});
	return array.join(",");
};
function TranList(list){
	var array=[];
	list.forEach(item=>{
		array.push(item);
	});
	return array;
};

function CheckUpdate(){
	const updateManager = uni.getUpdateManager();
	updateManager.onCheckForUpdate(function (res) {
	  // 请求完新版本信息的回调
	});
	
	updateManager.onUpdateReady(function (res) {
	  uni.showModal({
	    title: '更新提示',
	    content: '发现新版本，点击确定后将重启？',
	    success(res) {
	      if (res.confirm) {
	        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
			
	        updateManager.applyUpdate();
	      }
	    }
	  });
	
	});
	
	updateManager.onUpdateFailed(function (res) {
	  // 新的版本下载失败
	});
};
function DateDiff(interval,date1,date2){
	var dt1 =  Date.parse(date1.replace(/-/g, '/'));
	var dt2 = Date.parse(date2.replace(/-/g, '/'));
	var long = parseInt(dt2 - dt1); //相差毫秒
	switch(interval.toLowerCase()){
	case "y": return parseInt(long/1000/60/60/24/365);
	case "m": return parseInt(long/1000/60/60/24/30);
	case "d": return parseInt(long/1000/60/60/24);
	case "w": return parseInt(long/1000/60/60/24/7);
	case "h": return parseInt(long/1000/60/60);
	case "n": return parseInt(long/1000/60);
	case "s": return parseInt(long/1000);
	case "l": return parseInt(long);
	}
}
function SetParam(options){
	if (options.scene) {
	      var scene = decodeURIComponent(options.scene);
	      var sp = scene.split("-");
		  if(sp.length>=2){
			  uni.setStorageSync("ShopID",sp[0]);
			  uni.setStorageSync("ParentID",sp[1]);
		  }
	}
	if(options.ShopID){
		uni.setStorageSync("ShopID",options.ShopID);
	}
	if(options.ParentID){
		uni.setStorageSync("ParentID",options.ParentID);
	}
};
function AdSkip(item){
	if(item.Type==1){
		uni.navigateTo({
			url:'/pages/bookinfo/bookinfo?ID='+item.SID
		})
	}else if(item.Type==2){
		uni.navigateTo({
			url:'/pages/index/recommendbook?ID='+item.SID
		})
	}else if(item.Type==3){
		uni.navigateTo({
			url:'/pages/news/newsinfo?ID='+item.SID
		})
	}
};
function Auth(){
	if(App.User.ID>0 && App.User.CardNum!='' && App.User.OpenIDF==''){
		Confirm("授权给鲸鸿飞书公众号以接收通知？",json=>{
			uni.navigateTo({
				url:'/pages/index/auth'
			})
		});
	}
};
function ToSuccess(Url, TipText, BtnText, Delta){
	uni.navigateTo({
		url:"/pages/index/success?Url="+Url+"&TipText="+TipText+"&BtnText="+BtnText+"&Delta="+Delta
	})
};
function InitImg_Park_Sunmi(ewm, chapter, callback){
	var path1, path2;
	uni.getImageInfo({
		src: ewm,
		success: function(ret) {
		    path1 = ret.path;
		    uni.getImageInfo({
				src: chapter,
				success: function(ret) {
				   path2 = ret.path;
				   var canvas = uni.createCanvasContext('chapter')
				   canvas.drawImage(path1, 0, 18, 80, 80); //二维码
				   canvas.drawImage(path2, 102, 10, 90, 90); //公章
				   canvas.draw(false, ()=>{
					   if(callback){callback();}
				   }); 
				}
		    });
		}
	});
};
function InitImg_Easy_Sunmi(canvasid, width, height, url, callback){
	uni.getImageInfo({
		src: url,
		success: function(ret) {
		   var path1 = ret.path;
		   var canvas = uni.createCanvasContext(canvasid)
		   canvas.drawImage(path1, 0, 0, width, height);
		   canvas.draw(); 
		   if(callback){callback();}
		}
	});
};

function InitSignNameChapter_Easy_H96(signname, chapter, callback){
	var path1, path2;
	if(signname!=""){
		uni.getImageInfo({
			src: signname,
			success: function(ret) {
				path1 = ret.path;
				uni.getImageInfo({
					src: chapter,
					success: function(ret) {
					   path2 = ret.path;
					   var canvas = uni.createCanvasContext('chapter')
					   //#ifdef APP
					   canvas.translate(0, 240);
					   canvas.scale(1, -1); //上下镜像翻转，小程序里ios无效，只能后端实现
					   //#endif
					   canvas.drawImage(path1, 0, 0, 240, 96);
					   canvas.drawImage(path2, 320, 0, 240, 240);
					   //#ifdef APP
					   canvas.draw();
					   if(callback){callback();}
					   //#endif
					   //#ifdef MP-WEIXIN
					   canvas.draw(false, () => {ReverseChapter(callback);}); //垂直镜像翻转图片
					   //#endif
					}
				});
			}
		});
	}else{
		uni.getImageInfo({
			src: chapter,
			success: function(ret) {
			   path2 = ret.path;
			   var canvas = uni.createCanvasContext('chapter')		   
			   //#ifdef APP
			   canvas.translate(0, 240);
			   canvas.scale(1, -1); //上下镜像翻转，小程序里ios无效，只能后端实现
			   //#endif
			   canvas.drawImage(path2, 320, 0, 240, 240);
			   //#ifdef APP
			   canvas.draw();
			   if(callback){callback();}
			   //#endif
			   //#ifdef MP-WEIXIN
			   canvas.draw(false, () => {ReverseChapter(callback);}); //垂直镜像翻转图片
			   //#endif
			}
		});
	}
};
function InitSignName_Park_H96(signname,callback){
	uni.getImageInfo({
	    src: signname,
	    success: function(ret) {
	      var path = ret.path;
	      var canvas = uni.createCanvasContext('signname')
		  //#ifdef APP
		  canvas.translate(0, 120);
		  canvas.scale(1, -1); //上下镜像翻转
		  //#endif
	      canvas.drawImage(path, 100, 10, 240, 96);  
		  //#ifdef APP
	      canvas.draw()
		  if(callback){callback();}
		  //#endif
		  //#ifdef MP-WEIXIN
		  canvas.draw(false, () => {ReverseSignName(callback);}); //垂直镜像翻转图片
		  //#endif
	    }
	});
};
function InitEwmChapter_Park_H96(ewm,chapter,callback){
	var path1, path2;
	uni.getImageInfo({
		src: ewm,
		success: function(ret) {
			path1 = ret.path;
			uni.getImageInfo({
				src: chapter,
				success: function(ret) {
				    path2 = ret.path;
				    var canvas = uni.createCanvasContext('chapter')
				    //#ifdef APP
				    canvas.translate(0, 240);
				    canvas.scale(1, -1); //上下镜像翻转
				    //#endif
				    canvas.drawImage(path1, 0, 10, 200, 220);
				    canvas.drawImage(path2, 320, 0, 240, 240);
				    //#ifdef APP
				    canvas.draw();
				    if(callback){callback();}
					//#endif
					//#ifdef MP-WEIXIN
					canvas.draw(false, () => {ReverseChapter(callback);}); //垂直镜像翻转图片
					//#endif
				}
			});
		}
	});
};

function ReverseChapter(callback){
	uni.canvasGetImageData({
	    canvasId: 'chapter',
	    x: 0,
	    y: 0,
	    width: 560,
	    height: 240,
	    success: res => {
			var newlist=[];
	        for (var i = 0, h = res.height; i < h; i++) {
			   for (var j = 0, w = res.width; j < w; j++) {
				 newlist[i * w * 4 + j * 4 + 0] =res.data[(h - i) * w * 4 + j * 4 + 0];
				 newlist[i * w * 4 + j * 4 + 1] =res.data[(h - i) * w * 4 + j * 4 + 1];
				 newlist[i * w * 4 + j * 4 + 2] =res.data[(h - i) * w * 4 + j * 4 + 2];
				 newlist[i * w * 4 + j * 4 + 3] =res.data[(h - i) * w * 4 + j * 4 + 3];
			   }
			}
	        uni.canvasPutImageData({
	            canvasId: 'chapter',
	            data: new Uint8ClampedArray(newlist),
	            x: 0,
	            y: 0,
	            width: 560,
	            height: 240,
	        })
			if(callback){callback();}
	    }
	})
};
function ReverseSignName(callback){
	uni.canvasGetImageData({
	    canvasId: 'signname',
	    x: 0,
	    y: 0,
	    width: 560,
	    height: 120,
	    success: res => {
			var newlist=[];
	        for (var i = 0, h = res.height; i < h; i++) {
			   for (var j = 0, w = res.width; j < w; j++) {
				 newlist[i * w * 4 + j * 4 + 0] =res.data[(h - i) * w * 4 + j * 4 + 0];
				 newlist[i * w * 4 + j * 4 + 1] =res.data[(h - i) * w * 4 + j * 4 + 1];
				 newlist[i * w * 4 + j * 4 + 2] =res.data[(h - i) * w * 4 + j * 4 + 2];
				 newlist[i * w * 4 + j * 4 + 3] =res.data[(h - i) * w * 4 + j * 4 + 3];
			   }
			}
	        uni.canvasPutImageData({
	            canvasId: 'signname',
	            data: new Uint8ClampedArray(newlist),
	            x: 0,
	            y: 0,
	            width: 560,
	            height: 120,
	        })
			if(callback){callback();}
	    }
	})
};
function GetBase64(canvasid, width, height, callback){
	var time = setInterval(()=>{
		uni.canvasToTempFilePath({
			x: 0, // 起点坐标
			y: 0,
			width: width, // canvas 宽
			height: height, // canvas 高
			canvasId: canvasid, // canvas id
			fileType: 'jpg', 
			success:res=> {
				if(res.errMsg.indexOf("ok")>-1){
					clearInterval(time);
					const savedFilePath = res.tempFilePath //相对路径
					const path = plus.io.convertLocalFileSystemURL(savedFilePath) //绝对路径
					const fileReader = new plus.io.FileReader()
					fileReader.readAsDataURL(path)
					fileReader.onloadend = (json) => { //读取文件成功完成的回调函数
						if(callback){
							callback(json.target.result.replace("data:image/jpeg;base64,",""));
						}
					}
				}
				
			} 
		})
	},200);
};
module.exports = {
  Domain,
  FormatTime,
  Alert,
  Confirm,
  Toast,
  Success,
  Fail,
  Loading,
  HideLoading,
  Upload,
  OneUpload,
  ScanUpload,
  Post,
  PostAdmin,
  GetQueryString,
  GCJ02ToBaiDu,
  SetTabBarBadge,
  ListToImgs,
  ListToPaths,
  TranList,
  LoadMore,
  CheckUpdate,
  DownloadApp,
  DownloadWgt,
  DateDiff,
  SetParam,
  AdSkip,
  Auth,
  Audit,
  ToSuccess,
  InitSignNameChapter_Easy_H96,
  InitImg_Easy_Sunmi,
  InitImg_Park_Sunmi,
  InitEwmChapter_Park_H96,
  InitSignName_Park_H96,
  GetBase64
}
